"""
统一API响应格式模块

提供标准化的API响应格式，包括成功响应、错误响应和分页响应。
"""

from datetime import datetime, timezone
from typing import Any, Generic, TypeVar, Optional
from pydantic import BaseModel
from fastapi.responses import JSONResponse

T = TypeVar('T')


class ErrorDetail(BaseModel):
    """错误详情模型"""
    type: str
    field: str | None = None
    details: object | None = None
    trace_id: str | None = None


class Pagination(BaseModel):
    """分页信息模型"""
    total: int
    page: int
    size: int
    pages: int
    has_prev: bool = False
    has_next: bool = False


class ApiResponse(BaseModel, Generic[T]):
    """统一API响应模型"""
    success: bool
    code: int
    message: str
    data: Optional[T] = None
    error: Optional[ErrorDetail] = None
    timestamp: str = datetime.now(timezone.utc).isoformat()
    request_id: Optional[str] = None


class PaginatedResponse(BaseModel):
    """分页响应数据模型"""
    items: list[object]
    pagination: Pagination


def success_response(
    data: Any = None, 
    message: str = "操作成功", 
    code: int = 200,
    request_id: str | None = None
) -> dict[str, object]:
    """
    创建成功响应
    
    Args:
        data: 响应数据
        message: 响应消息
        code: 状态码
        request_id: 请求ID
        
    Returns:
        Dict: 标准化的成功响应
    """
    response = ApiResponse[Any](
        success=True,
        code=code,
        message=message,
        data=data,
        request_id=request_id
    )
    return response.model_dump(exclude_none=True)


def error_response(
    error_type: str,
    message: str = "操作失败",
    code: int = 400,
    field: str | None = None,
    details: object | None = None,
    trace_id: str | None = None,
    request_id: str | None = None
) -> dict[str, object]:
    """
    创建错误响应
    
    Args:
        error_type: 错误类型
        message: 错误消息
        code: 状态码
        field: 错误字段（验证错误时）
        details: 详细错误信息
        trace_id: 错误追踪ID
        request_id: 请求ID
        
    Returns:
        Dict: 标准化的错误响应
    """
    error_detail = ErrorDetail(
        type=error_type,
        field=field,
        details=details,
        trace_id=trace_id
    )
    response = ApiResponse[Any](
        success=False,
        code=code,
        message=message,
        error=error_detail,
        request_id=request_id
    )
    return response.model_dump(exclude_none=True)


def paginated_response(
    items: list[object],
    total: int,
    page: int,
    size: int,
    message: str = "获取成功",
    request_id: str | None = None
) -> dict[str, object]:
    """
    创建分页响应
    
    Args:
        items: 数据项列表
        total: 总记录数
        page: 当前页码
        size: 每页大小
        message: 响应消息
        request_id: 请求ID
        
    Returns:
        Dict: 标准化的分页响应
    """
    pages = (total + size - 1) // size if size > 0 else 0
    pagination = Pagination(
        total=total,
        page=page,
        size=size,
        pages=pages,
        has_prev=page > 1,
        has_next=page < pages
    )
    
    # 直接构建符合前端期望的响应格式
    response = ApiResponse[Any](
        success=True,
        code=200,
        message=message,
        data=items,  # 直接将items作为data
        request_id=request_id
    )
    
    # 将pagination作为顶级字段添加到响应中
    result = response.model_dump(exclude_none=True)
    result["pagination"] = pagination.model_dump()
    
    return result


def paginated_response_with_stats(
    items: list[object],
    total: int,
    page: int,
    size: int,
    statistics: dict[str, object] | None = None,
    message: str = "获取成功",
    request_id: str | None = None
) -> dict[str, object]:
    """
    创建带统计数据的分页响应
    
    Args:
        items: 数据项列表
        total: 总记录数
        page: 当前页码
        size: 每页大小
        statistics: 统计数据字典
        message: 响应消息
        request_id: 请求ID
        
    Returns:
        Dict: 标准化的带统计数据的分页响应
    """
    pages = (total + size - 1) // size if size > 0 else 0
    pagination = Pagination(
        total=total,
        page=page,
        size=size,
        pages=pages,
        has_prev=page > 1,
        has_next=page < pages
    )
    
    data = {
        "items": items,
        "pagination": pagination.model_dump()
    }
    
    # 如果提供了统计数据，添加到响应中
    if statistics:
        data["statistics"] = statistics
    
    return success_response(
        data=data, 
        message=message,
        request_id=request_id
    )


def json_response(
    content: dict[str, object],
    status_code: int = 200,
    headers: dict[str, str] | None = None
) -> JSONResponse:
    """
    创建JSON响应
    
    Args:
        content: 响应内容
        status_code: HTTP状态码
        headers: 响应头
        
    Returns:
        JSONResponse: FastAPI JSON响应对象
    """
    return JSONResponse(
        content=content,
        status_code=status_code,
        headers=headers or {}
    )


# 常用错误类型常量
class ErrorTypes:
    """错误类型常量"""
    NOT_FOUND: str = "NOT_FOUND"
    VALIDATION_ERROR: str = "VALIDATION_ERROR"
    AUTHENTICATION_ERROR: str = "AUTHENTICATION_ERROR"
    PERMISSION_ERROR: str = "PERMISSION_ERROR"
    NOT_FOUND_ERROR: str = "NOT_FOUND_ERROR"
    CONFLICT_ERROR: str = "CONFLICT_ERROR"
    INTERNAL_ERROR: str = "INTERNAL_ERROR"
    QUERY_ERROR: str = "QUERY_ERROR"
    STATS_ERROR: str = "STATS_ERROR"
    HTTP_ERROR: str = "HTTP_ERROR"
    INVALID_PARAMETER: str = "INVALID_PARAMETER"
    RATE_LIMIT_ERROR: str = "RATE_LIMIT_ERROR"
    ACCOUNT_LOCKED_ERROR: str = "ACCOUNT_LOCKED_ERROR"
    PERMISSION_DENIED_ERROR: str = "PERMISSION_DENIED_ERROR"
    DATABASE_ERROR: str = "DATABASE_ERROR"
    NOT_MODIFIED_ERROR: str = "NOT_MODIFIED_ERROR"
    IMPORT_TEMPLATE_ERROR: str = "IMPORT_TEMPLATE_ERROR" # 导入模板错误
    IMPORT_ERROR: str = "IMPORT_ERROR" # 导入错误
    EXPORT_ERROR: str = "EXPORT_ERROR" # 导出错误
    QUERY_ERROR: str = "QUERY_ERROR" # 查询错误
    CREATE_ERROR: str = "CREATE_ERROR" # 创建错误
    UPDATE_ERROR: str = "UPDATE_ERROR" # 更新错误
    DELETE_ERROR: str = "DELETE_ERROR" # 删除错误
    ARCHIVE_ERROR: str = "ARCHIVE_ERROR" # 归档错误
    RESTORE_ERROR: str = "RESTORE_ERROR" # 恢复错误


# 常用成功消息
class SuccessMessages:
    """成功消息常量"""
    OPERATION_SUCCESS: str = "操作成功"
    QUERY_SUCCESS: str = "查询成功"
    CREATE_SUCCESS: str = "创建成功"
    UPDATE_SUCCESS: str = "更新成功"
    DELETE_SUCCESS: str = "删除成功"
    ARCHIVE_SUCCESS: str = "归档成功"
    RESTORE_SUCCESS: str = "恢复成功"


# 常用错误消息
class ErrorMessages:
    """错误消息常量"""
    OPERATION_FAILED: str = "操作失败"
    VALIDATION_FAILED: str = "参数验证失败"
    AUTHENTICATION_FAILED: str = "认证失败"
    PERMISSION_DENIED: str = "权限不足"
    NOT_FOUND: str = "资源不存在"
    CONFLICT: str = "资源冲突"
    INTERNAL_ERROR: str = "服务器内部错误"
    QUERY_FAILED: str = "查询失败"
    CREATE_FAILED: str = "创建失败"
    UPDATE_FAILED: str = "更新失败"
    DELETE_FAILED: str = "删除失败"